package com.leetcode.LC;

import java.util.Stack;

public class LC445 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode a = l1, b = l2;
        ListNode d = new ListNode();
        int tmp = 0;
        Stack<Integer> stackA = new Stack<Integer>();
        Stack<Integer> stackB = new Stack<Integer>();
        while (a != null || b != null) {
            if (a != null) {
                stackA.push(a.val);
                a = a.next;
            }
            if (b != null) {
                stackB.push(b.val);
                b = b.next;
            }
        }

        while (!stackA.isEmpty() || !stackB.isEmpty()) {
            if (!stackA.isEmpty() && !stackB.isEmpty()) {
                d.val = (stackA.peek() + stackB.peek() + tmp) % 10;
                tmp = (stackA.pop() + stackB.pop() + tmp) / 10;
                ListNode node = new ListNode();
                node.next = d;
                d = node;
                //d=new ListNode().next=d;
                continue;
            }
            if (!stackA.isEmpty() && stackB.isEmpty()) {
                d.val = (stackA.peek() + tmp) % 10;
                tmp = (stackA.pop() + tmp) / 10;
                ListNode node = new ListNode();
                node.next = d;
                d = node;
                //d=new ListNode().next=d;
                continue;
            }
            if (stackA.isEmpty() && !stackB.isEmpty()) {
                d.val = (stackB.peek() + tmp) % 10;
                tmp = (stackB.pop() + tmp) / 10;
                ListNode node = new ListNode();
                node.next = d;
                d = node;
                //d=new ListNode().next=d;
                continue;
            }
        }
        if (tmp != 0) {
            d.val = tmp;
            return d;
        } else
            return d.next;
    }

    public static void main(String[] args) {

    }
}
